package com.feihong.yw189.paidan.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.astuetz.PagerSlidingTabStrip;
import com.feihong.yw189.R;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.paidan.adapter.DispatchAdapter;
import com.feihong.yw189.paidan.view.ViewPagerForMapView;
import com.meiqia.core.MQManager;
import com.meiqia.core.MeiQiaService;

import me.yokeyword.fragmentation.SupportActivity;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 派单界面
 */
@RuntimePermissions
public class DispatchActivity extends SupportActivity {
    private static final String TAG = "派单";
    private PagerSlidingTabStrip pagerSlidingTabStrip;
    private ViewPagerForMapView viewPager;
    private ImageView iv_back;

    private boolean isFirst = true;
    DispatchAdapter pagerAdapter;


    //设置android app 的字体大小不受系统字体大小改变的影响
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBarColor();
        setContentView(R.layout.activity_dispatch);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //禁止横竖屏切换
        initView();
        //关闭美洽服务
        MQManager.getInstance(this).setClientOffline();
        Intent intent = new Intent(this, MeiQiaService.class);
        stopService(intent);
    }
    public void setBarColor() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            View decorView = win.getDecorView();
            win.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | option);
                win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                win.setStatusBarColor(Color.TRANSPARENT);
            }
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        DispatchActivityPermissionsDispatcher.needpermissionWithCheck(DispatchActivity.this);
    }

    private void initView() {
        pagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        viewPager = (ViewPagerForMapView) findViewById(R.id.viewPager);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        pagerSlidingTabStrip.setIndicatorHeight(5);

        pagerAdapter = new DispatchAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);
        pagerSlidingTabStrip.setViewPager(viewPager);
        viewPager.setCurrentItem(0);
        /***
         * 解决地图和ViewPager的滑动
         */
        pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 1) {
                    //选择地图页面时，屏蔽viewPager的滑动
                    viewPager.setPagingEnabled(false);
                } else {
                    //选择其他页面时，恢复viewPager的滑动
                    viewPager.setPagingEnabled(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void needpermission() {

    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DispatchActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showRational(final PermissionRequest request) {
        new AlertDialog.Builder(DispatchActivity.this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取定位权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void Denied() {
        ToastUtils.showShortToast(DispatchActivity.this, "权限不足,您没有开启此应用的定位权限。请到系统设置-->权限管理 开启定位权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下定位权限！");
        finish();
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void AskAgin() {
        ToastUtils.showShortToast(DispatchActivity.this, "权限不足,您没有开启此应用的定位权限。请到系统设置-->权限管理 开启定位权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下定位权限！");
        finish();
    }
}
